package ar.org.sstuyv

import grails.converters.JSON

import org.apache.commons.logging.*

import org.springframework.dao.DataIntegrityViolationException

class ExpedienteController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

	private static Log log = LogFactory.getLog('error.' + ExpedienteController.class.getName())
	
    def index() {
        redirect(action: "list", params: params)
		log.info "Esto debería salir en pepito.log"
    }

    def list(Integer max) {
//        params.max = Math.min(max ?: 10, 100)
//        [expedienteInstanceList: Expediente.list(params), expedienteInstanceTotal: Expediente.count()]
		try{
		ver()
		}catch(Exception e ){
		log.error("list(Integer): " + e.getMessage())
		}
    }
	

	def listAdvancedJSON = {
		
//		def methods =['code', 'name', 'wonLeagues']
//		def dets = [] as Set
//
//		//def metodos = Partido.metaClass.properties.findAll { p -> println "${p.name} = ${p.type}" }
//		def m = methods.each {name ->  Partido.metaClass.properties.findAll { name == it} }
//		m.each { print it }
		
		
		def sortIndex = params.sidx ?: 'nombre'
		def sortOrder  = params.sord ?: 'asc'
		def maxRows = Integer.valueOf(params.rows)
		def currentPage = Integer.valueOf(params.page) ?: 1
		def rowOffset = currentPage == 1 ? 0 : (currentPage - 1) * maxRows
		
		def expedientes = Expediente.createCriteria().list(max: maxRows, offset: rowOffset) {
			if (params.id) eq('id', params.id.toLong())
			//methods.eachWithIndex { method ->
				//if(params."$method") ilike(method, "%${params.$method}%")
				
				//print "%${params.$method}%"
			//}
			
			if (params.numero) eq('codigo', params.codigo?.toInteger())
			if (params.alcance) ilike('partido', "%${params.nombre}%")
			if (params.cuerpo) ilike('codcatas', "%${params.codcatas}%")
			if (params.extracto) ilike('codcatas', "%${params.codcatas}%")
			if (params.fechaInicio) ilike('codcatas', "%${params.codcatas}%")
			if (params.tipoExpediente) ilike('codcatas', "%${params.codcatas}%")
			
			order(sortIndex, sortOrder)
		}
		
		def totalRows = expedientes.totalCount
		def numberOfPages = Math.ceil(totalRows / maxRows)
		
		def results = expedientes?.collect {
			[
				 cell: [it.id, it.numero, it.alcance, it.cuerpo, it.extracto, it.fechaInicio, it.tipoExpediente],
				 id: it.id
			]
		}

		
		def jsonData = [rows: results, page: currentPage, records: totalRows, total: numberOfPages]
		render jsonData as JSON
	}

    def create() {
        [expedienteInstance: new Expediente(params)]
    }

    def save() {
        def expedienteInstance = new Expediente(params)
        if (!expedienteInstance.save(flush: true)) {
            render(view: "create", model: [expedienteInstance: expedienteInstance])
            return
        }

        flash.message = message(code: 'default.created.message', args: [message(code: 'expediente.label', default: 'Expediente'), expedienteInstance.id])
        redirect(action: "show", id: expedienteInstance.id)
    }

    def show(Long id) {
        def expedienteInstance = Expediente.get(id)
        if (!expedienteInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'expediente.label', default: 'Expediente'), id])
            redirect(action: "list")
            return
        }

        [expedienteInstance: expedienteInstance]
    }

    def edit(Long id) {
        def expedienteInstance = Expediente.get(id)
        if (!expedienteInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'expediente.label', default: 'Expediente'), id])
            redirect(action: "list")
            return
        }

        [expedienteInstance: expedienteInstance]
    }

    def update(Long id, Long version) {
        def expedienteInstance = Expediente.get(id)
        if (!expedienteInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'expediente.label', default: 'Expediente'), id])
            redirect(action: "list")
            return
        }

        if (version != null) {
            if (expedienteInstance.version > version) {
                expedienteInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'expediente.label', default: 'Expediente')] as Object[],
                          "Another user has updated this Expediente while you were editing")
                render(view: "edit", model: [expedienteInstance: expedienteInstance])
                return
            }
        }

        expedienteInstance.properties = params

        if (!expedienteInstance.save(flush: true)) {
            render(view: "edit", model: [expedienteInstance: expedienteInstance])
            return
        }

        flash.message = message(code: 'default.updated.message', args: [message(code: 'expediente.label', default: 'Expediente'), expedienteInstance.id])
        redirect(action: "show", id: expedienteInstance.id)
    }

    def delete(Long id) {
        def expedienteInstance = Expediente.get(id)
        if (!expedienteInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'expediente.label', default: 'Expediente'), id])
            redirect(action: "list")
            return
        }

        try {
            expedienteInstance.delete(flush: true)
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'expediente.label', default: 'Expediente'), id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'expediente.label', default: 'Expediente'), id])
            redirect(action: "show", id: id)
        }
    }
	
	def ver(){
		[expedienteInstanceList: Expediente.findAllByPartido(Partido.findByNombre('LA PLATA')), expedienteInstanceTotal: Expediente.count()]
	}
	
	def listJson = {
		
		
//		def methods =['code', 'name', 'wonLeagues']
//		def dets = [] as Set
//
//		//def metodos = Partido.metaClass.properties.findAll { p -> println "${p.name} = ${p.type}" }
//		def m = methods.each {name ->  Partido.metaClass.properties.findAll { name == it} }
//		m.each { print it }
		
		
		def sortIndex = params.sidx ?: 'nombre'
		def sortOrder  = params.sord ?: 'asc'
		def maxRows = Integer.valueOf(params.rows)
		def currentPage = Integer.valueOf(params.page) ?: 1
		def rowOffset = currentPage == 1 ? 0 : (currentPage - 1) * maxRows
		
		def expedientes = Expediente.createCriteria().list(max: maxRows, offset: rowOffset) {
			if (params.id) eq('id', params.id.toLong())
			//methods.eachWithIndex { method ->
				//if(params."$method") ilike(method, "%${params.$method}%")
				
				//print "%${params.$method}%"
			//}
			
			if (params.numero) eq('codigo', params.codigo?.toInteger())
			if (params.alcance) ilike('partido', "%${params.nombre}%")
			if (params.cuerpo) ilike('codcatas', "%${params.codcatas}%")
			if (params.extracto) ilike('codcatas', "%${params.codcatas}%")
			if (params.fechaInicio) ilike('codcatas', "%${params.codcatas}%")
			if (params.tipoExpediente) ilike('codcatas', "%${params.codcatas}%")
			or{
				notEqual('numero', '')
			}
			order(sortIndex, sortOrder)
		}
		
		def totalRows = expedientes.totalCount
		def numberOfPages = Math.ceil(totalRows / maxRows)
		
		def results = expedientes?.collect {
			[
				 cell: [it.numero, it.alcance, it.cuerpo, it.extracto, it.fechaInicio, it.tipoExpediente],
				 id: it.numero
			]
		}

		
		def jsonData = [rows: results, page: currentPage, records: totalRows, total: numberOfPages]
		render jsonData as JSON
	
	}
	
	def listJsonCombo = {
		
		def lst = Expediente.findAll()
		
			StringBuffer buf = new StringBuffer("<select>")
			buf.append("<option value=\"${-1}\">")
			buf.append("")
			lst.each{
				buf.append("<option value=\"${it.id}\">")
				buf.append(it.toString())
				buf.append("</option>")
			}
			buf.append("</select>")
		
			render buf.toString()
	}
}
